package com.bluetane.examples.bluemote;

import com.bluetane.pc.BluetaneEvent;
import com.bluetane.pc.BluetaneListener;
import com.bluetane.pc.BtConnection;
import com.bluetane.pc.BtLocalDevice;
import com.bluetane.pc.BtRemoteDevice;
import javax.swing.JOptionPane;

public class Bluemote
{
    String[] deviceNames=null;
    BtLocalDevice btLocDev;

    BtRemoteDevice chosenRemoteDevice;

    Bluemote(){
        btLocDev = new BtLocalDevice("BlueMote v1");
        btLocDev.addEventListener(new BluetaneListener()
        {
            public void handleBluetaneEvent(BluetaneEvent event)
            {
                Object src=event.getSource();
                Object msg=event.getMessage();

                switch(event.getType()){
                    case DeviceFound://message is BtRemoteDevice
                        if(msg instanceof BtRemoteDevice){
                            deviceFound((BtRemoteDevice)msg);
                        }
                        else System.err.println("===Unexpected Message Type===");
                        break;

                    default:
                        System.out.println("===Unknown Update===\nType:    "+event.getType());
                        System.out.println("Message: "+event.getMessage());
                        System.out.println();
                        break;
                }
            }
        });

        //Start search for remote devices
        try{
            btLocDev.findRemotes();
        }catch(javax.bluetooth.BluetoothStateException e)
        {
            System.out.println("Caught exception: "+e);
        }
    }

    boolean searchComplete=false;
    void deviceFound(BtRemoteDevice device){
        //System.out.println("Found device: "+ device.getName() );
        if(searchComplete) return;
        int result = JOptionPane.showConfirmDialog(null,"Use device '"+device.getName()+"'?","Pick Device", JOptionPane.YES_NO_CANCEL_OPTION);
        if(result==JOptionPane.YES_OPTION){
            chosenRemoteDevice=device;
            startConnection(chosenRemoteDevice);
            searchComplete=true;
        }
        if(result==JOptionPane.CANCEL_OPTION){
            searchComplete=true;
        }
    }

    void remoteIsRunning(){
        startConnection(chosenRemoteDevice);
    }

    void startConnection(BtRemoteDevice remote){
        //Checks if app is running on device and tries to connect to it.
        btLocDev.connect(remote);//Android?
        //conn = btLocDev.awaitConnection(15);//PC?

        //ConnectionEstablished
//        conn.send("Monkeys");
//        System.out.println(conn.recieve());
//        conn.close();
    }

    public static void main(String[] args)
    {
        Bluemote main = new Bluemote();
        JOptionPane.showMessageDialog(null, "Press OK to quit BlueMote");
    }
    
}